/*
 * Copyright (C) 2012 DataSymphony (http://datasymphony.com.au)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package au.com.ds.restty.tester;

import java.util.HashMap;
import java.util.LinkedList;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TesterController {
	private HashMap<Integer, Item> mItems = new HashMap<Integer, Item>();
	
	@RequestMapping(value="/collection", method=RequestMethod.GET)
	public @ResponseBody Result onGetCollection(){
		return new Result("Success", new LinkedList<Item>(mItems.values()));
	}	
	
	@RequestMapping(value="/collection/{id}", method=RequestMethod.GET)
	public @ResponseBody Result onGetItem(@PathVariable int id){
		if (mItems.containsKey(id)){
			return new Result("Success", mItems.get(id));
		} else {
			return new Result("Error", "Invalid item id: " + id);
		}
	}	
	
	@RequestMapping(value="/collection", method=RequestMethod.PUT)
	public @ResponseBody Result onPutItem(@RequestBody Item item){
		String details = mItems.containsKey(item.getId()) ? "Item updated" : "Item created";
		mItems.put(item.getId(), item);
		return new Result("Success", details);
	}	
	
	@RequestMapping(value="/collection", method=RequestMethod.POST)
	public @ResponseBody Result onPostItem(@RequestBody Item[] items){
		mItems.clear();
		for (Item i : items){
			mItems.put(i.getId(), i);
		}
		return new Result("Success", "Collection replaced");
	}	

	@RequestMapping(value="/collection/{id}", method=RequestMethod.DELETE)
	public @ResponseBody Result onDeleteItem(@PathVariable int id){
		if (mItems.containsKey(id)){
			mItems.remove(id);
			return new Result("Success", "Item deleted: " + id);
		} else {
			return new Result("Error", "Invalid item id: " + id);
		}
	}	
}
